import requests
import re  # 正则

from bs4 import BeautifulSoup
import os

all_img_urls = []  # 所有图片链接

all_urls = [1, 2, 3, 4, 5]  # 当前总共5页

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/52.0.2743.116 Safari/537.36 "
}
jar = requests.cookies.RequestsCookieJar()


def getHtml(page: 1):
    return "https://www.toopic.cn/4kbz/?q=--81--.html&page=%s" % page


def create_dir_not_exist(path):
    if not os.path.exists(path):
        os.mkdir(path)


if __name__ == "__main__":
    pageUrl = []
    for i in all_urls:
        pageUrl.append(getHtml(page=i))
    print(pageUrl)
    index = 1
    imgName = 0

    create_dir_not_exist("./././images")
    for i in pageUrl:
        cook = requests.get(i).cookies
        res = requests.get(i, cookies=cook, headers=headers)
        html = BeautifulSoup(res.text, "html.parser")
        srcs = html.findAll("img")

        for item in srcs:
            imgName += 1
            with open("./././images/%s.jpg" % imgName, "wb") as f:
                f.write(
                    requests.get(
                        "https://www.toopic.cn%s" % item.get("data-original"),
                        headers=headers,
                    ).content
                )

        index += 1
